package com.LeeCode;

import java.util.HashMap;

/**
 * 最多 K 个重复元素的最长子数组
 */

public class Code2958 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 1, 2, 1, 2, 1, 2};
        int k = 1;
        System.out.println(new Code2958().maxSubarrayLength(nums, k));
    }

    public int maxSubarrayLength(int[] nums, int k) {
        int ans = 0, left = 0;
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
            while (map.get(nums[i]) > k) {
                map.put(nums[left], map.get(nums[left]) - 1);
                left++;
            }
            ans = Math.max(ans, i - left + 1);
        }
        return ans;
    }
}
